package com.zll.onlineExam.activities;

import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONObject;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.widget.button.roundbutton.RoundButton;
import com.zll.onlineExam.R;
import com.zll.onlineExam.ajax.Ajax;
import com.zll.onlineExam.ajax.HTTPConfig;
import com.zll.onlineExam.ajax.ReqCallback;
import com.zll.onlineExam.db.DBHelper;
import com.zll.onlineExam.entity.out.ProductionDtoOut;
import com.zll.onlineExam.entity.out.UserDtoOut;
import com.zll.onlineExam.utils.GlobalDataHolder;
import com.zll.onlineExam.utils.XToastUtils;

import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProductionContentActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView mBack;
    private TextView mTopTitle;

    private LinearLayout mInfoContent;
    private LinearLayout mImgContent;
    private TextView mTitle;
    private TextView mType;
    private TextView mBrand;
    private TextView mPrice;
    private TextView mScore;
    private TextView mDescription;
    private TextView mSize;
    private TextView mStock;
    private RoundButton mExchange;
    private RoundButton mExchangeFalse;

    private ImageOptions imageOptions;

    private static Handler mHandler;
    private Map<String, Object> parmas;
    private SQLiteDatabase db;

    private final int FETCH_SUCCESS = 1;
    private final int FETCH_FAIL = 0;
    private final int FETCH_ERROR = -1;
    private final int COMMIT_SUCCESS = 4;
    private final int FLUSH_FAIL = 5;
    private final int COMMIT_FAIL = 3;
    private final int COMMIT_ERROR = 2;

    private static DataHolder mHolder;

    private static final String TAG = "===ProductionContent";

    private class DataHolder {
        private ProductionDtoOut data;

        public ProductionDtoOut getData() {
            return data;
        }

        public DataHolder setData(ProductionDtoOut data) {
            this.data = data;
            return this;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_production_content);
        imageOptions = new ImageOptions.Builder()
                // 如果ImageView的大小不是定义为wrap_content, 不要crop.
                .setCrop(true) // 很多时候设置了合适的scaleType也不需要它.
                // 加载中或错误图片的ScaleType
                //.setPlaceholderScaleType(ImageView.ScaleType.MATRIX)
                .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
                .setPlaceholderScaleType(ImageView.ScaleType.CENTER_CROP)
                .setLoadingDrawableId(R.drawable.ic_default_img)
                .setFailureDrawableId(R.drawable.ic_default_img)
                .setIgnoreGif(false)
                .build();

        initView();
        initListener();
        initHandler();
        initData();
        mHolder = new DataHolder();
        db = DBHelper.getDB(this);
    }

    private void initHandler() {
        mHandler = new Handler() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case FETCH_SUCCESS:
                        loadData();
                        break;
                    case COMMIT_SUCCESS:
                        XToastUtils.success("兑换成功");
                        mExchange.setVisibility(View.GONE);
                        mExchangeFalse.setVisibility(View.VISIBLE);
                        getUserInfo();
                        break;
                    case FLUSH_FAIL:
                        XToastUtils.error("刷新用户信息失败");
                        break;
                    case FETCH_FAIL:
                        XToastUtils.error("获取失败");
                        break;
                    case FETCH_ERROR:
                        XToastUtils.error("网络异常");
                        break;
                    default:
                        break;
                }

            }
        };
    }

    private void initView() {
        mBack = findViewById(R.id.iv_back);
        mTopTitle = findViewById(R.id.a_de_title);
        mTitle = findViewById(R.id.tv_title);
        mType = findViewById(R.id.tv_type);
        mBrand = findViewById(R.id.tv_brand);
        mPrice = findViewById(R.id.tv_price);
        mScore = findViewById(R.id.tv_score);
        mDescription = findViewById(R.id.tv_desc);
        mSize = findViewById(R.id.tv_size);
        mStock = findViewById(R.id.tv_stock);
        mInfoContent = findViewById(R.id.production_content_layout);
        mImgContent = findViewById(R.id.production_imgs_layout);
        mExchange = findViewById(R.id.b_exchange);
        mExchangeFalse = findViewById(R.id.b_exchange_false);

    }

    private void initListener() {
        mBack.setOnClickListener(this);
        mExchange.setOnClickListener(this);
    }

    private void initData() {
        parmas = new HashMap<>();
        String pid = getIntent().getStringExtra("pid");
        parmas.put("pid", pid);
        parmas.put("uid", GlobalDataHolder.getInstance().getCurUser().getUid());
        Ajax.post(HTTPConfig.LIST_PRODUCTION, parmas, new ReqCallback() {
            @Override
            public void onSuccess(JSONObject resp) {
                List<ProductionDtoOut> dtos = resp.getJSONArray("data").toJavaList(ProductionDtoOut.class);
                if (dtos.size() != 1){
                    mHandler.sendEmptyMessage(FETCH_FAIL);
                }else{
                    mHolder.setData(dtos.get(0));
                    mHandler.sendEmptyMessage(FETCH_SUCCESS);
                }
            }

            @Override
            public void onFail(String msg) {
                mHandler.sendEmptyMessage(FETCH_FAIL);
            }

            @Override
            public void onError(String msg) {
                mHandler.sendEmptyMessage(FETCH_ERROR);
            }
        });
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            finish();
        }
        if (id == R.id.b_exchange){
            doExchange();
        }
    }

    private void loadData(){
        mTitle.setText(mHolder.getData().getTitle());
        mBrand.setText(mHolder.getData().getBrandName());
        mType.setText(mHolder.getData().getType());
        mPrice.setText(mHolder.getData().getPrice());
        mScore.setText(mHolder.getData().getBonusScore());
        mSize.setText(mHolder.getData().getSize());
        mStock.setText(String.valueOf(mHolder.getData().getStock()));
        mDescription.setText(mHolder.getData().getUsage());

        mInfoContent.setVisibility(View.VISIBLE);
        // 兑换按钮
        boolean enable = Integer.parseInt(GlobalDataHolder.getInstance().getCurUser().getScore()) > Integer.parseInt(mHolder.getData().getBonusScore())
                && mHolder.getData().getStock() > 0
                && mHolder.getData().getExchangeScore() == 0;
        Log.d(TAG, "兑换: "+enable);
        if (enable){
            mExchange.setVisibility(View.VISIBLE);
            mExchangeFalse.setVisibility(View.GONE);
        }else{
            mExchange.setVisibility(View.GONE);
            mExchangeFalse.setVisibility(View.VISIBLE);
            if (mHolder.getData().getExchangeScore() != 0){
                mExchangeFalse.setText("已兑换");
            }
        }

        // 添加图片
        if (mHolder.getData().getPictureList() != null && mHolder.getData().getPictureList().size()>0){
            for (String imgName: mHolder.getData().getPictureList()){
                ImageView iv = new ImageView(this);
                iv.setPadding(DensityUtils.dp2px(this, 2),DensityUtils.dp2px(this, 2),DensityUtils.dp2px(this, 2),DensityUtils.dp2px(this, 2));
                if (!imgName.startsWith("http")) {
                    imgName = HTTPConfig.API+ HTTPConfig.IMG_PREFIX + imgName;
                }
                Log.d(TAG, "get IMG"+imgName);
                x.image().bind(iv,imgName,this.imageOptions);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
                params.gravity = Gravity.CENTER_HORIZONTAL;
                mImgContent.addView(iv,params);
            }
            mImgContent.setVisibility(View.VISIBLE);
        }
    }

    // 执行兑换
    private void doExchange(){
        parmas = new HashMap<>();
        String pid = getIntent().getStringExtra("pid");
        parmas.put("pid", pid);
        parmas.put("uid", GlobalDataHolder.getInstance().getCurUser().getUid());
        parmas.put("exchangeScore", mHolder.getData().getBonusScore());
        Ajax.post(HTTPConfig.EXCHANGE_PRODUCTION, parmas, new ReqCallback() {
            @Override
            public void onSuccess(JSONObject resp) {
                mHandler.sendEmptyMessage(COMMIT_SUCCESS);
            }

            @Override
            public void onFail(String msg) {
                mHandler.sendEmptyMessage(FETCH_FAIL);
            }

            @Override
            public void onError(String msg) {
                mHandler.sendEmptyMessage(FETCH_ERROR);
            }
        });
    }

    private void getUserInfo() {
        Ajax.post(HTTPConfig.FlUSH, new HashMap<>(), new ReqCallback() {
            @Override
            public void onSuccess(JSONObject resp) {
                GlobalDataHolder.getInstance().setCurUser(resp.getObject("data", UserDtoOut.class));
                DBHelper.initUser(db, resp.getObject("data", Map.class));
                Ajax.setToken(DBHelper.checkDBAndGetToken(db));
            }

            @Override
            public void onFail(String msg) {
                mHandler.sendEmptyMessage(FLUSH_FAIL);
            }

            @Override
            public void onError(String msg) {
                mHandler.sendEmptyMessage(FETCH_ERROR);
            }
        });
    }
}